package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.tanhua.admin.mapper.AnalysisByDayMapper;
import com.tanhua.model.admin.AnalysisByDay;
import com.tanhua.model.admin.AnalysisSummaryVo;
import com.tanhua.model.admin.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class DashboardService {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    /**
     *      新增用户数
     * @param sd
     * @param ed
     * @return
     */
    public Map<String, Object> getUsersCount(Long sd, Long ed) {
        List<Users> thisYear = new ArrayList<>();
        List<Users> lastYear = new ArrayList<>();
        String start = new SimpleDateFormat("yyyy-MM-dd").format(sd);
        String end = new SimpleDateFormat("yyyy-MM-dd").format(ed);
        int thisYear1 = DateUtil.thisYear() - 1;
        String laststart = thisYear1 + "-" + new SimpleDateFormat("MM-dd").format(sd);
        String lastend = thisYear1 + "-" +  new SimpleDateFormat("MM-dd").format(ed);
        List<AnalysisByDay> analysis = analysisByDayMapper.getRegistered(start,end);
        for (AnalysisByDay analysisByDay : analysis) {
            Users user = new Users();
            Date date = new Date(analysisByDay.getRecordDate().getTime());
            user.setTitle(new SimpleDateFormat("dd").format(date));
            user.setAmount(analysisByDay.getNumRegistered());
            thisYear.add(user);
        }


        List<AnalysisByDay> lastYearList = analysisByDayMapper.getRegistered(laststart,lastend);
        for (AnalysisByDay analysisByDay : lastYearList) {
            Users user = new Users();
            Date date = new Date(analysisByDay.getRecordDate().getTime());
            user.setTitle(new SimpleDateFormat("dd").format(date));
            user.setAmount(analysisByDay.getNumRegistered());
            lastYear.add(user);
        }


        Map<String,Object> map = new HashMap<String, Object>();
        map.put("thisYear",thisYear);
        map.put("lastYear",lastYear);
        return map;
    }

    /**
     *  概要统计信息
     * @return
     */
    public AnalysisSummaryVo getSummary() {
        String today = DateUtil.today();
        String yesterday = DateUtil.yesterday().toDateStr();

        String last7day = DateUtil.offsetDay(new Date(),-7).toDateStr();
        String last30day = DateUtil.offsetDay(new Date(),-30).toDateStr();

        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        //累计用户数
        vo.setCumulativeUsers(analysisByDayMapper.selectUsers());
        //过去30天活跃用户数
        vo.setActivePassMonth(analysisByDayMapper.selectLastDay(last30day));
        //过去7天活跃用户数
        vo.setActivePassWeek(analysisByDayMapper.selectLastDay(last7day));

        // 今日数据
        AnalysisByDay todayData = analysisByDayMapper.findByRecordDate(today);
        vo.setNewUsersToday(todayData.getNumRegistered());
        vo.setLoginTimesToday(todayData.getNumLogin().longValue());
        vo.setActiveUsersToday(todayData.getNumActive().longValue());
        AnalysisByDay yesterdayData = analysisByDayMapper.findByRecordDate(yesterday);
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        vo.setNewUsersTodayRate(computeRate(todayData.getNumRegistered().longValue(),yesterdayData.getNumRegistered().longValue()));
        vo.setLoginTimesTodayRate(computeRate(todayData.getNumLogin().longValue(),yesterdayData.getNumLogin().longValue()));
        vo.setActiveUsersTodayRate(computeRate(todayData.getNumActive().longValue(),yesterdayData.getNumActive().longValue()));

        return vo;
    }

    /**
     *      计算环比数
     * @param current
     * @param last
     * @return
     */
    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }

    /**
     *      统计
     * @param sd
     * @param ed
     * @return
     */
    public Map<String, Object> getUsersByType(Long sd, Long ed) {
        String start = new SimpleDateFormat("yyyy-MM-dd").format(sd);
        String end = new SimpleDateFormat("yyyy-MM-dd").format(ed);
        int thisYear1 = DateUtil.thisYear() - 1;
        String laststart = thisYear1 + "-" + new SimpleDateFormat("MM-dd").format(sd);
        String lastend = thisYear1 + "-" +  new SimpleDateFormat("MM-dd").format(ed);
        List<Users> thisYear = new ArrayList<>();
        List<Users> lastYear = new ArrayList<>();

        List<AnalysisByDay> analysisList = analysisByDayMapper.getRegistered(start,end);
        for (AnalysisByDay analysis : analysisList) {
            Users user = new Users();
            Date date = new Date(analysis.getRecordDate().getTime());
            user.setTitle(new SimpleDateFormat("dd").format(date));
            user.setAmount(analysis.getNumActive());
            thisYear.add(user);
        }

        List<AnalysisByDay> lastYearList = analysisByDayMapper.getRegistered(laststart,lastend);
        for (AnalysisByDay analysis : lastYearList) {
            Users user = new Users();
            Date date = new Date(analysis.getRecordDate().getTime());
            user.setTitle(new SimpleDateFormat("dd").format(date));
            user.setAmount(analysis.getNumActive());
            lastYear.add(user);
        }
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("thisYear",thisYear);
        map.put("lastYear",lastYear);
        return map;
    }
}
